package cn.wh.netty.pojo;


import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HongXiaoHan
 * @Description Client与userId的关联处理
 * @Date: 2021/2/9 11:38
 */
public class UserMapManagement {
    public static HashMap<String, SignalClient> userChannel = new HashMap<>();

    public static void put(String userId, SignalClient client) {
        userChannel.put(userId, client);
    }

    //获取client
    public static SignalClient get(String userId) {
        return userChannel.get(userId);
    }

    public static SignalClient remove(String userId) {
        return userChannel.remove(userId);
    }

    public static void removeByChanelId(Channel channel) {
        String channelId = channel.id().asShortText();
        System.out.println("客户端被移除：channel id 为：" + channelId);
        // 获取channel对应的userId
        String userId = null;
        for (Map.Entry<String, SignalClient> entry : UserMapManagement.userChannel.entrySet()) {
            if (entry.getValue().getChannel() == channel) {
                userId = entry.getKey();
                break;
            }
        }
        if (userId != null) {
            UserMapManagement.remove(userId);
            System.out.println("用户 " + userId + " 的连接已断开");
        }
    }

    public static void main(String[] args) {
        //测试
        double random = Math.random();
        System.out.println(random);

    }

}
